package com.basic.app.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.basic.app.entity.member.LoginUser;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        LoginUser user = new LoginUser();
        user.setUsername("1");
        user.setUsername("213");
        System.out.println(user);
    }
    //加密
    public static String encryptPassword(String userName,String password, String idCardNum){
        JSONObject subject = JSONUtil.createObj()
                .set("userName", userName)
                .set("password", password)
                .set("idCardNum", idCardNum);
        try {
            return Test.createJWT(userName,JSONUtil.toJsonStr(subject),-1);
        } catch (Exception e) {
           e.printStackTrace();
           return "";
        }
    }
    // 解密
    public static String parsePassword(String password)throws Exception{
        Claims claims = Test.parseJWT(password);
        JSONObject subject = JSONUtil.parseObj(claims, false);
        return subject.getStr("password");
    }

    public static String SECRETKEY = "11111111212121hsodhsdhasdhsaldhsalhdlsahdlsad";

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey(String stringKey) {
        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(stringKey));
        return key;
    }

    /**
     * 创建jwt
     * @param id 唯一id，uuid即可
     * @param subject json形式字符串或字符串，增加用户非敏感信息存储，如用户id或用户账号，与token解析后进行对比，防止乱用
     * @param expirationDate  生成jwt的有效期，单位秒
     * @return jwt token
     * @throws Exception
     */
    public static String createJWT(String userName, String subject, long expirationDate) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey(SECRETKEY);
        JwtBuilder builder = Jwts.builder()
                .setIssuer("111")
                .setId(userName)
                .setIssuedAt(now)
                .setSubject(subject)
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(key, signatureAlgorithm);
        if (expirationDate >= 0) {
            long expMillis = nowMillis + expirationDate*1000;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密jwt，获取实体
     * @param jwt
     */
    public static Claims parseJWT(String jwt) {
        SecretKey key = generalKey(SECRETKEY);
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
        return claims;
    }



}
